package models

import (
	"github.com/jinzhu/gorm"
	"time"
)

type Storage struct {
	Model

	Name    string `json:"name"`
	Address string `json:"address"`
	Type    int    `json:"type"`
	Remark  string `json:"remark"`
	Status  int    `json:"status"`
}

//创建时自动执行
func (Storage *Storage) BeforeCreate(scope *gorm.Scope) error {
	scope.SetColumn("CreateTime", time.Now().Unix())
	scope.SetColumn("UpdateTime", time.Now().Unix())
	return nil
}

//修改时自动执行
func (Storage *Storage) BeforeUpdate(scope *gorm.Scope) error {
	scope.SetColumn("UpdateTime", time.Now().Unix())
	return nil
}

func GetStorage(pageNum int, pageSize int, maps interface{}) (storage []Storage) {
	db.Where(maps).Where("status=?", 1).Offset(pageNum).Limit(pageSize).Find(&storage)
	return
}

func GetStorageById(id int) (*Storage, error) {
	var storage Storage
	err := db.Where("id=?", id).Find(&storage).Error
	if err != nil {
		return nil, err
	}
	return &storage, nil
}

func GetStorageTotal(maps interface{}) (total int) {
	db.Model(&Storage{}).Where(maps).Count(&total)
	return
}

func ExistStorageByName(name string) bool {
	var storage Storage
	db.Select("id").Where("name=?", name).First(&storage)
	if storage.ID > 0 {
		return true
	}
	return false
}

func AddStorage(name string, address string, type_ int, remark string) bool {
	db.Create(&Storage{
		Name:    name,
		Address: address,
		Type:    type_,
		Remark:  remark,
		Status:  1,
	})
	return true
}

func ExistStorageById(id int) bool {
	var storage Storage
	db.Select("id").Where("id=?", id).First(&storage)
	if storage.ID > 0 {
		return true
	}
	return false
}

func DeleteStorageById(id int) bool {
	err := db.Model(&Storage{}).Where("id=?", id).Update("status", 0).Error
	if err != nil {
		return false
	}
	return true
}

func EditStorage(id int, data interface{}) bool {
	db.Model(&Storage{}).Where("id=?", id).Update(data)
	return true
}
